package cn.zero.letaomallspringboot.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {
    // 生产环境从配置读取，长度至少256位
    private static final String SECRET = "mySecretKeyForJWT";
    // 24小时过期
    private static final long EXPIRATION_TIME = 86400000L;

    /**
     * 生成JWT token
     */
    public static String createToken(String userId, String username) {
        return Jwts.builder()
                .setSubject(username)
                .claim("userId", userId)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 解析token获取Claims
     */
    public static Claims getClaimByToken(String token) {
        if (token == null) {
            return null;
        }
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 从token获取userId
     */
    public static String getUserIdByToken(String token) {
        Claims claims = getClaimByToken(token);
        if (claims == null) {
            return null;
        }
        return claims.get("userId", String.class);
    }

    /**
     * 检查token是否过期
     */
    public static boolean isTokenExpired(String token) {
        Claims claims = getClaimByToken(token);
        return claims == null || claims.getExpiration().before(new Date());
    }
}